//
//  HomeViewController.m
//  HWZB
//
//  Created by 许成雄 on 2017/4/13.
//  Copyright © 2017年 wonders. All rights reserved.
//

#import "HomeViewController.h"
#import "TopScrollTableViewCell.h"
#import "OilCardTableViewCell.h"
#import "RechargeCardTableViewCell.h"
#import "MobilePhoneTableViewCell.h"
#import "CommodityDetailViewController.h"
#import "BannerDetailViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "QRCodeScanViewController.h"
#import "NSString+Utils.h"
#import "HWZBAPIRequest.h"

//下拉刷新，上拉加载
#import <MJRefresh/MJRefresh.h>
#import "MyRefreshHeader.h"


@interface HomeViewController () <UITableViewDelegate, UITableViewDataSource, TopScrollTableViewCellDelegate, OilCardTableViewCellDelegate, MobilePhoneTableViewCellDelegate, UIActionSheetDelegate, AVCaptureMetadataOutputObjectsDelegate> {
    AVCaptureSession *session;
    AVCaptureVideoPreviewLayer *layer;
}

@property (strong, nonatomic) UIBarButtonItem *scanButton;
@property (strong, nonatomic) UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *bannerArray;
@property (strong, nonatomic) NSMutableArray *oilCardArray;
@property (strong, nonatomic) NSMutableArray *rechargeCardArray;
@property (strong, nonatomic) NSMutableArray *mobilePhoneArray;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = I_COLOR_BACKGROUND;
    self.navigationItem.title = @"铧为至宝";
    
    [self createUI];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

#pragma mark - UIButton Action
//通过扫描获取二维码
- (void)scanButtonAction {
    // 1、 获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (status == AVAuthorizationStatusNotDetermined) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        QRCodeScanViewController *vc = [[QRCodeScanViewController alloc] init];
                        vc.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:vc animated:YES];
                    });
                    SGQRCodeLog(@"当前线程 - - %@", [NSThread currentThread]);
                    // 用户第一次同意了访问相机权限
                    SGQRCodeLog(@"用户第一次同意了访问相机权限");
                } else {
                    // 用户第一次拒绝了访问相机权限
                    SGQRCodeLog(@"用户第一次拒绝了访问相机权限");
                }
            }];
        } else if (status == AVAuthorizationStatusAuthorized) { // 用户允许当前应用访问相机
            QRCodeScanViewController *vc = [[QRCodeScanViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        } else if (status == AVAuthorizationStatusDenied) { // 用户拒绝当前应用访问相机
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"警告" message:@"请去-> [设置 - 隐私 - 相机 - SGQRCodeExample] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            [alertC addAction:alertA];
            [self presentViewController:alertC animated:YES completion:nil];
        } else if (status == AVAuthorizationStatusRestricted) {
            NSLog(@"因为系统原因, 无法访问相册");
        }
    } else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alertController addAction:alertAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - Private Method
- (void)createUI {
    
//    UIButton *scanCustomView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 19 + 6, 22)];
//    scanCustomView.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//    [scanCustomView setImage:[UIImage imageNamed:@"ic_navi_scan"] forState:UIControlStateNormal];
//    [scanCustomView setImage:[UIImage imageNamed:@"ic_navi_scan"] forState:UIControlStateFocused];
//    [scanCustomView setImage:[UIImage imageNamed:@"ic_navi_scan"] forState:UIControlStateSelected];
//    [scanCustomView addTarget:self action:@selector(scanButtonAction) forControlEvents:UIControlEventTouchUpInside];
//    self.scanButton = [[UIBarButtonItem alloc] initWithCustomView:scanCustomView];
//    self.navigationItem.rightBarButtonItem = self.scanButton;
    
    //实例化表单控件
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = I_DIVIDER_COLOR;
    self.tableView.backgroundColor = I_COLOR_WHITE;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, TRANS_VALUE(0.0f))];
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20.0f)];
    footerView.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = footerView;
    //设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    MyRefreshHeader *header = [MyRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_header = header;

    //设置tableview分割线
    if([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }

}

- (void)loadData {
    //获取首页轮播图
    [self getHomeBannerInfo];
    
    //获取首页商品信息
    [self getHomeCommoditiesInfo];
}

- (void)getHomeBannerInfo {
    if(!self.bannerArray) {
        self.bannerArray = [NSMutableArray arrayWithCapacity:0];
    }
    [self.bannerArray removeAllObjects];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
    [[HWZBAPIRequest sharedInstance] getHomeBannerWithParams:params success:^(NSArray *bannerArray) {
        if(bannerArray != nil) {
            [self.bannerArray addObjectsFromArray:bannerArray];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"%@", error.localizedDescription);
        [self.tableView reloadData];
    }];
}

- (void)getHomeCommoditiesInfo {
    if(!self.rechargeCardArray) {
        self.rechargeCardArray = [NSMutableArray arrayWithCapacity:0];
    }
    [self.rechargeCardArray removeAllObjects];
    
    if(!self.oilCardArray) {
        self.oilCardArray = [NSMutableArray arrayWithCapacity:0];
    }
    [self.oilCardArray removeAllObjects];
    
    if(!self.mobilePhoneArray) {
        self.mobilePhoneArray = [NSMutableArray arrayWithCapacity:0];
    }
    [self.mobilePhoneArray removeAllObjects];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
    [params setObject:@"0" forKey:@"isIndex"];
    [params setObject:@"1" forKey:@"page"];
    [[HWZBAPIRequest sharedInstance] getHomeCommoditiesWithParams:params success:^(NSArray *commodityArray) {
        [self.tableView.mj_header endRefreshing];
        if(commodityArray != nil) {
            [self sortCommodityList:commodityArray];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"%@", error.localizedDescription);
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    }];
}

//将产品列表分类
- (void)sortCommodityList:(NSArray *)commodityArray {
    for(int i = 0, n = (int)commodityArray.count; i < n; i++ ) {
        CommodityInfo *commodityInfo = (CommodityInfo *)[commodityArray objectAtIndex:i];
        if([commodityInfo.typeId isEqualToString:@"1"]) {
            [self.oilCardArray addObject:commodityInfo];
        } else if([commodityInfo.typeId isEqualToString:@"2"]) {
            [self.rechargeCardArray addObject:commodityInfo];
        } else {
            [self.mobilePhoneArray addObject:commodityInfo];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - TopScrollTableViewCellDelegate
- (void)didClickTopBannerInfo:(HomeBannerInfo *)bannerInfo {
    if(bannerInfo && ![NSString isBlankString:bannerInfo.wxmpUrl]) {
        BannerDetailViewController *bannerDetailViewController = [[BannerDetailViewController alloc] init];
        bannerDetailViewController.bannerInfo = bannerInfo;
        bannerDetailViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:bannerDetailViewController animated:YES];
    }
}

#pragma mark - OilCardTableViewCellDelegate
- (void)clickOilCardForItem:(CommodityInfo *)cardInfo {
    if(cardInfo) {
        CommodityDetailViewController *commodityDetailViewController = [[CommodityDetailViewController alloc] init];
        commodityDetailViewController.commodityId = cardInfo.commodityId;
        commodityDetailViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:commodityDetailViewController animated:YES];
    }
}

#pragma mark - MobilePhoneTableViewCellDelegate
- (void)clickMobilePhoneForItem:(CommodityInfo *)mobilePhoneInfo {
    if(mobilePhoneInfo) {
        CommodityDetailViewController *commodityDetailViewController = [[CommodityDetailViewController alloc] init];
        commodityDetailViewController.commodityId = mobilePhoneInfo.commodityId;
        commodityDetailViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:commodityDetailViewController animated:YES];
    }
}

#pragma mark - UITableViewDelegate && UITableViewDatesource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0) {
        return 1;
    } else if(section == 1) {
        NSInteger count = self.oilCardArray != nil && self.oilCardArray.count % 2 == 0 ? self.oilCardArray.count / 2 : (self.oilCardArray.count / 2 + 1);
        return count;
    } else if(section == 2){
        NSInteger count = self.rechargeCardArray != nil && self.rechargeCardArray.count > 0 ? self.rechargeCardArray.count : 0;
        return count;
    } else {
       NSInteger count = self.mobilePhoneArray != nil && self.mobilePhoneArray.count % 2 == 0 ? self.mobilePhoneArray.count / 2 : (self.mobilePhoneArray.count / 2 + 1);
        return count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        return TRANS_VALUE(98.0f);
    } else if(indexPath.section == 1) {
        return TRANS_VALUE(86.0f);
    } else if(indexPath.section == 2) {
        return TRANS_VALUE(102.0f);
    } else {
        return TRANS_VALUE(86.0f);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(section == 0) {
        return 0.0f;
    } else {
        return TRANS_VALUE(25.0f);
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if(section == 0) {
        CGFloat height = TRANS_VALUE(0.0f);
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
        return view;
    } else  {
        NSString *titleStr = @"油卡充值套餐";
        if(section == 1) {
            titleStr = @"油卡充值套餐";
        } else if(section == 2) {
            titleStr = @"充值卡";
        } else if(section == 3) {
            titleStr = @"手机";
        }
        UIView *view = [self sectionHeaderWithTitle:titleStr inSection:section];
        return view;
    }
}

- (UIView *)sectionHeaderWithTitle:(NSString *)title inSection:(NSInteger)section {
    CGFloat height = TRANS_VALUE(25.0f);
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
    view.backgroundColor = I_COLOR_WHITE;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(TRANS_VALUE(10.0f), TRANS_VALUE(10.0f), TRANS_VALUE(200.0f), TRANS_VALUE(15.0f))];
    titleLabel.textColor = I_COLOR_33BLACK;
    titleLabel.font = [UIFont boldSystemFontOfSize:TRANS_VALUE(12.0f)];
    titleLabel.text = title;
    [view addSubview:titleLabel];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(section == 1) {
        return TRANS_VALUE(0.0f);
    } else {
        return 0.0f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if(section == 1) {
        CGFloat height = TRANS_VALUE(0.0f);
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
        view.backgroundColor = RGBCOLOR(247, 247, 247);
        return view;
    } else {
        CGFloat height = TRANS_VALUE(0.0f);
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
        view.backgroundColor = I_COLOR_WHITE;
        return view;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0) {
        static NSString *identifier = @"TopScrollTableViewCell";
        TopScrollTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if(!cell) {
            cell = [[TopScrollTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        }
        if(indexPath.row < 1) {
            //TOOD -- 滚动banner
            cell.delegate = self;
            cell.topList = self.bannerArray;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if(indexPath.section == 1) {
        static NSString *identifier = @"OilCardTableViewCell";
        OilCardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if(!cell) {
            cell = [[OilCardTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        }
        NSInteger count = self.oilCardArray != nil && self.oilCardArray.count % 2 == 0 ? self.oilCardArray.count / 2 : (self.oilCardArray.count / 2 + 1);
        if(indexPath.row < count) {
            //TOOD -- 我的任务
            CommodityInfo *oilCardInfo = (CommodityInfo *)[self.oilCardArray objectAtIndex:2 * indexPath.row];
            cell.oilCardItem1 = oilCardInfo;
            
            CommodityInfo *oilCardInfo2 = nil;
            if(indexPath.row * 2 + 1 < [self.oilCardArray count]) {
                 oilCardInfo2 = (CommodityInfo *)[self.oilCardArray objectAtIndex:indexPath.row + 1];
            }
            cell.oilCardItem2 = oilCardInfo2;
        }
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if(indexPath.section == 2) {
        static NSString *identifier = @"RechargeCardTableViewCell";
        RechargeCardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if(!cell) {
            cell = [[RechargeCardTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        }
        cell.rechargeCardInfo = [[CommodityInfo alloc] init];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        static NSString *identifier = @"MobilePhoneTableViewCell";
        MobilePhoneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if(!cell) {
            cell = [[MobilePhoneTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        }
        NSInteger count = self.mobilePhoneArray != nil && self.mobilePhoneArray.count % 2 == 0 ? self.mobilePhoneArray.count / 2 : (self.mobilePhoneArray.count / 2 + 1);
        if(indexPath.row < count) {
            //TOOD -- 我的任务
            CommodityInfo *mobilePhoneInfo1 = (CommodityInfo *)[self.mobilePhoneArray objectAtIndex: 2 * indexPath.row];
            cell.mobilePhoneItem1 = mobilePhoneInfo1;
            CommodityInfo *mobilePhoneInfo2 = nil;
            if(indexPath.row * 2 + 1 < [self.oilCardArray count]) {
                mobilePhoneInfo2 = (CommodityInfo *)[self.mobilePhoneArray objectAtIndex:2 * indexPath.row + 1];
            }
            cell.mobilePhoneItem2 = mobilePhoneInfo2;
        }
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 2){
        CommodityDetailViewController *commodityDetailViewController = [[CommodityDetailViewController alloc] init];
        CommodityInfo *rechargeCardInfo = (CommodityInfo *)[self.rechargeCardArray objectAtIndex:indexPath.row];
        commodityDetailViewController.commodityId = rechargeCardInfo.commodityId;
        commodityDetailViewController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:commodityDetailViewController animated:YES];
    }
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 1) {
        if(indexPath.row < self.oilCardArray.count) {
            if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
            if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                [cell setLayoutMargins:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
        } else {
            if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
            if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                [cell setLayoutMargins:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
        }
    } else if(indexPath.section == 2){
        if(indexPath.row < self.mobilePhoneArray.count) {
            if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
            if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                [cell setLayoutMargins:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
        } else {
            if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
            if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                [cell setLayoutMargins:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
        }
    } else if(indexPath.section == 3){
        if(indexPath.row < self.rechargeCardArray.count) {
            if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
            if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                [cell setLayoutMargins:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
        } else {
            if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                [cell setSeparatorInset:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
            if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                [cell setLayoutMargins:UIEdgeInsetsMake(0, SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2)];
            }
        }
    }
    
}

//uitableview处理section的不悬浮，禁止section停留的方法，主要是这段代码
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    CGFloat sectionHeaderHeight = TRANS_VALUE(150.0f);
//    if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
//        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//    } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
//        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
//    }
//}

@end
